import Api from "@/api/index.jsx";
import { setPermissions, setRoles, setUserInfo } from "@/store/modules/user.jsx";
import { setFullRouteMenu, setLayoutRouteMenu, setMenu, setSidebarMenu } from "@/store/modules/menu.jsx";
import React, { Suspense } from "react";
import { Spin } from "antd";
import { basicRouter } from "@/router/index.jsx";

let flag = false;
const loading = Boolean(import.meta.env.VITE_PAGE_LOADING);
const fullScreenRoutes = [];
let LayoutRoutes = [];
const module = await import("@/store");
const ComponentRoute = (element) => {
  if (!element) return false;
  const LazyComponent = React.lazy(() => import(/* @vite-ignore */ `/src/pages${element}.jsx`));
  return (
    <Suspense fallback={loading && <Spin spinning={true} fullscreen tip={"页面加载中"}></Spin>}>
      <LazyComponent></LazyComponent>
    </Suspense>
  );
};
const setLayMenu = (menu) => {
  return menu
    .filter((item) => !item.hidden)
    .map((item) => ({
      ...item,
      ...(item.children && {
        children: setLayMenu(item.children),
      }),
    }));
};
const setRouterMenu = (menu) => {
  return menu.map((item) => {
    const routeObj = {
      path: item.path,
      element: ComponentRoute(item.element),
      cache: item.cache || false,
      full: item.full || false,
      meta: item.meta || {},
    };
    if (item.children && item.children.length) {
      routeObj.children = setRouterMenu(item.children);
    }
    return routeObj;
  });
};
const setFullRoutes = (routes) => {
  LayoutRoutes = routes.filter((item) => {
    if (item.full) {
      fullScreenRoutes.push(item);
      return false;
    }
    if (item.children) {
      item.children = setFullRoutes(item.children);
    }
    return true;
  });
  return LayoutRoutes;
};
const initRoutes = async () => {
  await Api.getRouters().then(async (res) => {
    if (res.code === 200) {
      module.store.dispatch(setMenu(res.data || []));
      return new Promise((resolve) => {
        const { menuStore } = module.store.getState();
        const menu = JSON.parse(JSON.stringify(menuStore.menu)); //克隆后端路由数据
        const LayoutMenu = setLayMenu(menu); //左侧菜单需要展示的
        const detalRoutes = setRouterMenu(menu); //添加路由菜单
        setFullRoutes(detalRoutes);
        module.store.dispatch(setSidebarMenu(LayoutMenu)); //存储
        module.store.dispatch(setFullRouteMenu(fullScreenRoutes));
        module.store.dispatch(setLayoutRouteMenu(LayoutRoutes));
        basicRouter[1].children = LayoutRoutes || [];
        basicRouter.push(...fullScreenRoutes);
        resolve();
        flag = true;
      });
    }
  });
};
export default async function DynamicRouters() {
  await Api.Info().then(async (res) => {
    if (res.code === 200) {
      module.store.dispatch(setUserInfo(res.user));
      module.store.dispatch(setPermissions(res.user));
      module.store.dispatch(setRoles(res.user));
      await initRoutes();
    }
  });
  return flag;
}
